/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-09-10 09:33:28
 * @filename : mobile/static/logic/nmm/src/views/searchOpt.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module){

    require('{component}promptTip/promptTip.css');
    var SearchOptView,userObj,
        mId = 'searchOpt',reRender = false,menuName='searchOpt',
        imglazyload = require('{component}imglazyload/zepto.imglazyload'),
        promptTip = require('{component}promptTip/promptTip'),
        panel = require('{component}panel/zepto.panel'),
        tpl = require('{view}searchOpt.tpl'),
        tplC  = require('{view}countryList.tpl'),
        tplN = require('{view}userNav.tpl'),
        tplS  = require('{view}stateList.tpl');

    SearchOptView = Backbone.View.extend({

        el: '',

        template: _.template(tpl),
        templateN: _.template(tplN),
        templateC: _.template(tplC),
        templateS: _.template(tplS),

        initialize: function () {},

        render: function (obj) {
            if (!share.checkPermission(true)){return;};
            share.reRender(reRender,mId);

            if ($('#'+mId).length < 1) { 
                $('body').append(this.template(lang)); 
                if ($('#userNav').length < 1) { 
                    $('body').append(this.templateN(lang));
                    panel.info.state = 'show';
                    panel.init();
                    $('#userNav').imglazyload({startY : 0,endY: $(window).height(),sW:50,sH:50}); 
                }
               
                var userInfo = share.userInfo();
                userObj = share.getObjStorage(userInfo.usr_id);
                this.bindEvt();
                this.initData(); 
                this.initCountryList();
                //this.initIncomeList();
            } else {
                $('#'+mId).css('display','block');
                //dialog.close({dom:$('#'+mId)});
            }

            share.panel(panel,this.templateN,mId,menuName);

        },

        bindEvt : function() {
            var tthis = this,dom = $('#'+mId);

            dom.find('.left').on('tap',function(e){
                window.location.href = '#userList/whole'; 
            });

            dom.find('.seekinga').find('li').on('tap',function(){
                tthis.setMatchGender(this); 
            });

            dom.find('.toggleButton').on('tap',function() {
                if(tthis.checkIsGuest()){return};
                var str = $(this).attr('class'),
                    replaceStr = tthis.toggleButton(str); 
                    $(this).attr('class',replaceStr); 
            });
            /*
            $('#searchOpt #income').live('change.searchOpt',function(e){
                if(tthis.checkIsGuest()){
                    $(this).find('option').eq(0).attr('selected',true);
                    return;
                };
            });
            */
            $('#searchOpt #ethnicity').live('change.searchOpt',function(e){
                if(tthis.checkIsGuest()){
                    $(this).find('option').eq(0).attr('selected',true);
                    return;
                };
            });
            
            /*
            $('#searchOpt #search_photo').live('change.searchOpt',function(e){
                if(tthis.checkIsGuest()){
                    $(this).find('option').eq(0).attr('selected',true);
                    return;
                };
            });
            */

            $('#searchOpt #country').live('change.searchOpt',function(){
                var val = $(this).find('option:selected').val();
                tthis.initStateList(val);
            });

            dom.find('.fromAge').find('select').on('change.searchOpt',function(){
                var valF = $(this).find('option:selected').val(),
                    valT = dom.find('.toAge').find('select').find('option:selected').val();
                valT = valF > valT ? valF : valT; 
                tthis.toAgeSelect(valF,valT); 
            });

            dom.find('.right').on('tap',function(){
                tthis.setSearchVal();
            });
        },

        initData : function() {
            if (userObj.match.match_gender == 1) {
                var that = $('#'+mId).find('.seekinga').find('li').eq(1);
                this.setMatchGender(that);
            } else if (userObj.match.match_gender == 2) {
                var that = $('#'+mId).find('.seekinga').find('li').eq(0);
                this.setMatchGender(that);
            } else {
                var that = $('#'+mId).find('.seekinga').find('li').eq(2);
                this.setMatchGender(that);
            }

            $('#'+mId).find("#from_age").find("option[value='"+userObj.match.match_age_min+"']").attr('selected',true);
            this.toAgeSelect(userObj.match.match_age_min);
            $('#'+mId).find("#to_age").find("option[value='"+userObj.match.match_age_max+"']").attr('selected',true);
        },

        toAgeSelect : function(val,valT) {
            var html = '<select id="to_age" class="age_group">'+
                '<option value="" disabled selected></option>';
            for (var i = val; i<100; i++) { 
                if (i == valT) {
                    html = html+'<option value='+i+' selected>'+i+'</option>';
                } else { 
                    html = html+'<option value='+i+'>'+i+'</option>';
                }
            }
            $('#'+mId).find('.toAge').html(html);
        },

        setMatchGender : function(that) {
            $(that).parent().find("li").each(function(){
                var type = $(this).removeAttr('class').find('span').attr('type');
                $(this).find('span').removeAttr('class').addClass(type);
            });

            var type = $(that).find('span').attr('type');
            $(that).addClass('libg_'+type).find('span').removeAttr('class').addClass('select_'+type);
        },

        toggleButton : function(str) {
            if (str.indexOf(' on') > -1) {
                str = str.replace(' on',' off');
            } else if (str.indexOf(' off') > -1){
                str = str.replace(' off',' on');
            }
            return str;
        },
 
        initCountryList : function() {
            share.getCountryList({callback:this.renderCountryDom,that:this}); 
        },

        renderCountryDom : function(data,obj) {
            $('#'+mId).find('.country').html(obj.that.templateC({ arr: data.data, val: userObj.account.country, search:true}));
            obj.that.initStateList(userObj.account.country);
        },

        initStateList : function(val) {
            if (val == '') {
                this.clearState(); 
                return;
            }

            val = parseInt(val);
            if (val !== 0 && val !== 31 && val !== 180) {
                share.getStateList({callback:this.renderStateDom,that:this, country:val}); 
            } else {
                this.clearState();
            };
        },
        
        clearState : function() {
            var stateobj = $('#'+mId).find('.state');
            if (stateobj !== undefined) {
                stateobj.html('');
            }
        },

        renderStateDom : function(data,obj) {
            if (data.data.length > 0 ) {
                $('#'+mId).find('.state').html(obj.that.templateS({ arr: data.data,val:userObj.account.state,search:true}));
            } else {
                this.that.clearState();                       
            }

        },

        checkIsGuest : function() {
            var bool = false;
            if (share.isGuest()) {
                var tthis = this,
                    input = $('#'+mId).find('input'),
                    select = $('#'+mId).find('select');
                    input.blur();
                    select.blur();
                setTimeout(function(){
                    tthis.openDialog();
                },500);
                bool = true;
            } 
            return bool;
        },

        openDialog : function() {
            promptTip.show({type:'btn',btnText:'Upgrade',text:'Upgrade now to enjoy full search.',dom:$('#'+mId).find('.promptTip'),time:3000,callback:function(){window.location.href = '#upgrade/whole';}});
        },

        setSearchVal : function() {
            var  obj={},dom = $('#'+mId);
               
            obj.match_gender = dom.find('.seekinga').find('li[class]').find('span').data('gender');
            obj.match_age_min = dom.find('#from_age').find('option:selected').val();
            obj.match_age_max = dom.find('#to_age').find('option:selected').val();
            obj.r_country = dom.find("#country option:selected").val();
            

            if (obj.r_country && parseInt(obj.r_country) !== 0 && parseInt(obj.r_country) !== 31 && parseInt(obj.r_country) !== 180) {
                obj.match_r_state_id = dom.find('#state option:selected').val();
            }

            obj.keywords = dom.find('.keywords').find('input').val();
            obj.match_ethnicity = dom.find('#ethnicity option:selected').val();
 
            /*
            obj.last_online = dom.find('#last_online option:selected').val(); 

            if(obj.last_online !== '') {
               obj.last_online = parseInt(obj.last_online) * 24 * 3600;
            }
            */

            if(!share.isGuest()){
               //obj.search_photo = dom.find("#search_photo option:selected").val();
               //obj.type = dom.find('#income option:selected').val();
               //obj.income_verify = dom.find('.search-verified').find('span').hasClass('on') ? 1 : 0;
               obj.search_photo = dom.find('.search-photo').find('span').hasClass('on') ? 1 : 0;
               obj.attractiveness = dom.find('.search-newmember').find('span').hasClass('on') ? 1 : 0;
            }

            obj.page_num = 0;
            obj.offset = 20;
            //console.log('search',obj);
            share.userListSearch = {};
            for(var i in obj) {
                if (obj[i] !== undefined && obj[i] !== '') {
                    share.userListSearch[i] = obj[i];
                }
            }
             
            //console.log('share.search',share.userListSearch);
            window.location.href = '#userList/whole/customSearch'; 
        } 

    });
    module.exports = SearchOptView;
})
  
